<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Admin extends Admin_Controller {

	var $theme_data = array(
		'layout_main' => 'layout',
		'left' => 'include/leftcp',
		);

	public $model = "admin";
	public $view = "admin";
	public $permissionCreate = 'Admin.Create';
	public $permissionDelete = 'Admin.Delete';
	public $permissionEdit   = 'Admin.Edit';
	public $permissionView   = 'Admin.View';
	protected $index_show = array(
		array( 'field' => 'admin_id',
			'label' => 'Admin id'),	
		array( 'field' => 'admin_account',
			'label' => 'Account',
				'custom_value' => '<a href="{url_edit}{admin_id}">{admin_account}</a>', //replace value
				),
		array( 'field' => 'admin_email',
			'label' => 'Email'),
		);
	function __construct() {
		parent::__construct();
		$this->load->model($this->model.'_m',$this->model);
		$this->_model = $this->{$this->model};
		$this->load->model('Roles_m','role');
		$this->load->event('admin');
	}
	function index($page = 0)
	{
		// Events::trigger('Admin.Index', $page, 'string');
		return parent::index($page);
		$this->load->library('grocery_CRUD');
		$this->load->library('crud_callback');
		$crud = new grocery_CRUD();
		$crud->set_table($this->db->dbprefix('admins'));
		$crud->unset_jquery();
		// $crud->unset_columns('admin_password','admin_salt2auth','admin_salt');
		$crud->field_type('admin_status','dropdown', array( 1 => 'Sử dụng', 0 => 'Khóa'));
		$crud->field_type('admin_password', 'password');
		// $crud->change_field_type('admin_salt', 'invisible');
		$crud->set_field_upload('admin_avatar','images/admin_avatar');
		$crud->callback_column('admin_time_create',array($this->crud_callback,'_format_time'));
		$crud->fields('admin_account','admin_email','admin_time_create','admin_status','display_name','admin_avatar','role_id','admin_password');

		$crud->callback_before_insert(array($this->admin,'update_password'));
		$crud->callback_before_update(array($this->admin,'update_password'));

		$crud->set_relation('role_id','roles','role_name');
		$output = $crud->render();
		$this->theme_data["main"] = "include/crud";
		$this->template->viewAdmin($this->theme_data, $output);
	}
	function edit($edit_id = 0) {
		
		$this->data['roles'] = array();
		$roles = $this->role->get_many_by();
		if($roles)
			foreach($roles as $role)
			{
				$this->data['roles'][$role->role_id] = $role->role_name;
			}
			parent::edit($edit_id);
		}

		public function login() {
			$data = array();
			$post = $this->input->post();
			$this->load->library('GoogleAuthenticator');
			if ($post) {
				$username = $post['username'];
				$password = $post['password'];
				$admin = $this->admin->get_by('admin_account', $username);
				if ($admin) {
					$this->data['admin'] = $admin;
					if($admin->admin_status ==0)
					{
						$this->log_activity->add('Admin login', $username.' đăng nhập với tài khoản bị khóa.','error');
						$this->messages->add('Tài khoản của bạn đã bị khóa, vui lòng liên hệ với Quản trị để biết thêm chi tiết.','error');

					} else if ($this->admin->compare_password($password, $admin->admin_password, $admin->admin_salt)) {
						
						$this->data['admin']->auth2step = json_decode($admin->admin_salt2auth);
						if($this->data['admin']->auth2step->status == TRUE)
						{
							$this->session->set_userdata(array(
								'temp_admin_id' => $this->data['admin']->admin_id,
								'auth2step' => TRUE,
								));
							redirect(admin_url().'admin/auth2steplogin', 'location');
						}
						else
						{
							$role = $this->role->get($admin->role_id);
							$admin->role_name = '';
							if($role)
							{
								$admin->role_name = $role->role_name;
							}
							$this->admin->setLogin($admin);
							$this->log_activity->add('Admin login', $username.' đăng nhập thành công','success');
							redirect(admin_url(), 'location');
						}
						$this->log_activity->add('Admin login', $username.' đăng nhập không thành công','error');
						$this->messages->add('Không đúng mật khẩu hoặc username, vui lòng kiểm tra lại.','error');
					}
				}
				else
				{
					$this->log_activity->add('Admin login', $username.' đăng nhập không thành công','error');
					$this->messages->add('Không đúng mật khẩu hoặc username, vui lòng kiểm tra lại.','error');
				}
			}
			$this->theme_data["left"] = null;
			$this->theme_data["main"] = "admin/login";
			$this->template->viewAdmin($this->theme_data, $data);
		}

		public function logout() {
			$this->admin->logout();
			redirect(base_url(), 'location');
		}

		function profile()
		{
		//$this->auth->restrict('Admin.Profile');
			$data = array();
			if($post = $this->input->post())
			{
				$this->admin->update($this->admin->id, $post['edit']);
				$this->log_activity->add('Admin profile', 'Cập nhật thông tin cá nhân','success');
				$this->messages->add('Cập nhật thành công.','success');
			}
			$data['edit'] = $this->admin->get($this->admin->id);
			$data['role'] = $this->role->get($data['edit']->role_id);
			$this->theme_data["main"] = "admin/profile";
			$this->template->viewAdmin($this->theme_data, $data);
		}

		function inserttxt($code = ''){
			$account = 'HT-'.rand(0,1000);
			$pass = '123';
			$salt = 'ABC123';

			$this->admin->insert(array(
				'admin_account' =>$account,
				'admin_password' =>$this->admin->hash_pass($pass,$salt),
				'admin_salt' =>$salt,
				));
			echo $account.' - '.$pass;
		}

		function ajax_upload($admin_id = 0){
			require(APPPATH.'libraries/FileUpload.php');
			$this->load->model('simage');
			$admin_id = $this->admin->id;
			$admin = $this->_model->get($admin_id);
			if(!$admin) die('Admin id not found');
			$uploader = new FileUpload('admin_avatar');
			$this->folder_upload = "images/admin_avatar/";
			if($admin_id <=0) die();
			$this->simage->create_dirs($this->folder_upload);

			$uploader->allowedExtensions = array('jpg', 'jpeg', 'png', 'gif','swf');
			$uploader->sizeLimit = 91071520;
			if($admin->admin_avatar == '')
			{
				$uploader->newFileName = 'admin-'.$admin_id.'-'.uniqid().'.'.$uploader->getExtension();
			}
			else
			{
				$avatar_name = basename($admin->admin_avatar);
				$avatar_name = explode(".", $avatar_name);
				array_pop($avatar_name);

				$uploader->newFileName = implode('.', $avatar_name).'.'.$uploader->getExtension();
			}
			$result = $uploader->handleUpload('./'.$this->folder_upload);
			if (!$result) {
				echo json_encode(array(
					'success' => false,
					'msg' => $uploader->getErrorMsg()
					));    

			} else {
				if(!is_array($admin_id)) {

					$this->_model->update($admin_id, array(
						'admin_avatar' => $this->folder_upload.''.$uploader->getFileName(),
						));
					
				$config['image_library'] = 'gd2';
				$config['source_image'] = './'.$this->folder_upload.''.$uploader->getFileName();
				$config['maintain_ratio'] = FALSE;
				$config['width']         = 160;
				$config['height']       = 160;
				$this->load->library('image_lib', $config);

				$this->image_lib->resize();
				$admin->admin_avatar = $this->folder_upload.''.$uploader->getFileName();
				$admin->role_id = $this->admin->role_id;
				$admin->role_name = $this->admin->role_name;
				$this->log_activity->add('Admin Update Avatar', 'Cập nhật avatar','success');
				$this->admin->setLogin($admin);
				echo json_encode(array(
					'success' => true,
					'file' => base_url().$this->folder_upload.''.$uploader->getFileName()."?v=".time(),
					));
				}


			}
		}

		function auth2steplogin()
		{
			$this->load->library('GoogleAuthenticator');
			if($this->session->userdata('auth2step') && $admin_id = $this->session->userdata('temp_admin_id'))
			{
				$this->data['admin']  = $this->admin->get($admin_id);
				if($this->input->post() && $verify_code = $this->input->post('verify_code'))
				{
					$this->data['admin']->auth2step = json_decode($this->data['admin']->admin_salt2auth);
					if($this->data['admin']->auth2step->status == TRUE)
					{
						$result = $this->googleauthenticator->verifyCode($this->data['admin']->auth2step->code, $verify_code, 2);
						if($result)
						{
							$role = $this->role->get($this->data['admin']->role_id);
							$this->data['admin']->role_name = '';
							if($role)
							{
								$this->data['admin']->role_name = $role->role_name;
							}
							$this->admin->setLogin($this->data['admin']);
							redirect(admin_url(), 'location');
						}
						else
						{
							$this->messages->add('Mã xác minh không đúng, vui lòng kiểm tra lại','error');
						}
					}
					else
					{
						$this->admin->setLogin($this->data['admin']);
						redirect(admin_url(), 'location');
					}
					
				}

				$this->theme_data["left"] = null;
				$this->theme_data["main"] = "admin/auth2steplogin";
				$this->template->viewAdmin($this->theme_data, $this->data);
			}
			else
			{
				$this->messages->add('Vui lòng đăng nhập bằng mật khẩu trước. Mã lỗi Admin.1110','error');
				redirect(admin_url(), 'location');
			}
			
		}
	/*
		Xác minh đăng nhập 2 bước
	*/
		function auth2step()
		{
			$this->data['edit'] = $this->admin->get($this->admin->id);
			$this->load->library('GoogleAuthenticator');
			$this->data['edit']->auth2step = json_decode($this->data['edit']->admin_salt2auth);

			if(!$this->data['edit']->auth2step)
			{

				$this->data['edit']->auth2step = new stdClass();
				$this->data['edit']->auth2step->status = FALSE;
				$this->data['edit']->auth2step->code =  $this->googleauthenticator->createSecret();
				$this->admin->update($this->admin->id, array(
					'admin_salt2auth' => json_encode($this->data['edit']->auth2step)
					));
			}
			$this->data['qrCodeUrl'] = $this->googleauthenticator->getQRCodeGoogleUrl('CMS Admin Auth', $this->data['edit']->admin_email, $this->data['edit']->auth2step->code);

			if($this->input->post())
			{
				if($this->input->post('authcheck'))
				{
					$this->data['edit']->auth2step->status = TRUE;
					if($codeauth = $this->input->post('codeauth'))
					{
						$checkResult = $this->googleauthenticator->verifyCode($this->data['edit']->auth2step->code, $codeauth, 2);
						if ($checkResult) {
							$this->data['edit']->auth2step->status = TRUE;
							$this->admin->update($this->admin->id, array(
								'admin_salt2auth' => json_encode($this->data['edit']->auth2step)
								));
							$this->messages->add('Cập nhật thành công.','success');
						} else {
							$this->messages->add('Mã xác nhận không chính xác, vui lòng thử lại','error');
						}
					}
					else
					{
						$this->messages->add('Mã xác nhận không chính xác, vui lòng thử lại','error');
					}
				}
				else
				{
					$this->data['edit']->auth2step->status = FALSE;
					$this->data['edit']->auth2step->code =  $this->googleauthenticator->createSecret();
					$this->admin->update($this->admin->id, array(
						'admin_salt2auth' => json_encode($this->data['edit']->auth2step)
						));
					$this->messages->add('Cập nhật thành công.','success');
				}
				
			}

			$this->theme_data["main"] = "admin/auth2step";
			$this->template->viewAdmin($this->theme_data, $this->data);
		}
	}
